from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
from odoo.exceptions import ValidationError

class ProductCategory(models.Model):
    _inherit = 'product.category'
    '''当供应商价格是按销售价格乘以价格系数得到的，就用以下方法添加或更新供应商价格表'''

    pricexs = fields.Float(string='价格系数(采购价格=销售价*该系数)')
    partner_id = fields.Many2one(string = '供应商',comodel_name ='res.partner',domain=[('supplier', '=', True)])
    min_qty = fields.Float('最少订货量', default=1, required=True,
        help="The minimal quantity to purchase from this vendor, expressed in the vendor Product Unit of Measure "
             "if not any, in the default unit of measure of the product otherwise.")
    delay = fields.Integer(
        '交货期（天）', default=1, required=True,
        help="Lead time in days between the confirmation of the purchase order and the receipt of the products in your "
             "warehouse. Used by the scheduler for automatic computation of the purchase order planning.")

    # supplierinfo_update = fields.Boolean(string='要更新采购价？',help="按销售价格乘以系数得到采购价格的产品分类，可以勾选此项")
    cost_update = fields.Boolean(string='更新成本价？',help='批量更新standard_price')
    import_purchase=fields.Boolean(string='只导入更新采购价格',default=False)
    rate = fields.Float(string='涨价系数(%)',digits=(5,4),default=0)
    datestart=fields.Date('价格起效日期', help="设置该值作为该价格起作用日期")
    dateend=fields.Date('价格失效日期')

    def action_import(self):
        return {
            'name': '销售价导入及采购价和成本更新',
            'res_model': 'import.wizard',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'views': [[self.env.ref('mlupdate.view_import_excel_wizard').id, 'form']],
            'target': 'new',
            'context': {'category_id': self.id,'import_purchase':self.import_purchase},
        }

    #根据价格系数，将产品进价乘以该价格系数
    @api.multi
    def update_supplierinfo(self):
        if not self.partner_id:
            raise ValidationError('No partner!')
        categ_id=self.id
        pricexs=self.pricexs
        vendor_id=self.partner_id.id
        delay=self.delay
        # min_qty=self.min_qty
        datestart=fields.Date.to_string(self.datestart)
        dateend=fields.Date.to_string(self.dateend)
        if pricexs:  
            #下面通过sql语句返回最近一次修改supplierinfo
            self.env.cr.execute("""select max(s.id) as sid from product_supplierinfo s,product_template p  
            where p.id=s.product_tmpl_id and p.list_price !=0 and s.name=%s and p.categ_id=%s   
            group by product_tmpl_id""",(vendor_id,categ_id))
            sids=self.env.cr.fetchall()
            for s in sids:
                supplierinfo=self.env['product.supplierinfo'].browse(s)
                sinfo=supplierinfo.copy({
                    'price':supplierinfo.product_tmpl_id.list_price*pricexs,
                    'date_revised':fields.Date.today(),#将更新日期填入
                    'date_start':datestart,
                    'date_end':dateend,
                    'delay':delay
                })
                if self.cost_update: #如果要更新成本价
                    self.update_cost(sinfo)
    @api.multi
    def update_cost(self,sinfo):
        fields_id=self.env['ir.model.fields'].search([('name', '=', 'standard_price'),('model','=','product.product')]).id #字段的id号
        prdt_tmpl_id = sinfo.product_tmpl_id.id
        prdt_id=self.env['product.product'].search([('product_tmpl_id','=',prdt_tmpl_id)]).id
        ir=self.env['ir.property'].search([('res_id','=','product.product,' + str(prdt_id)),
                                ('fields_id','=',fields_id),('company_id','=',self.env.user.company_id.id)]) #查看是否已经有成本价了
        if ir:
            ir.value_float = round(sinfo.price/1.13,2)
        else:
            values = {
                'value_float': round(sinfo.price/1.13,2),
                'type': 'float',
                'name': 'standard_price',
                'res_id': 'product.product,%s' % str(prdt_id),
                'fields_id': fields_id,
                'company_id': self.env.user.company_id.id
            }
            ir.create(values)
        return
    #根据涨价幅度百分比，将销售价及采购价调整   
    @api.multi
    def action_adjust(self):
        if not self.partner_id:
            raise ValidationError('No partner!')
        categ_id=self.id
        rate=self.rate/100
        vendor_id=self.partner_id.id
        datestart=fields.Date.to_string(self.datestart)
        dateend=fields.Date.to_string(self.dateend)
        delay=self.delay
        #下面通过sql语句返回最近一次修改supplierinfo
        self.env.cr.execute("""select max(s.id) as sid from product_supplierinfo s,product_template p  
        where p.id=s.product_tmpl_id and p.list_price !=0 and s.name=%s and p.categ_id=%s   
        group by product_tmpl_id""",(vendor_id,categ_id))
        sids=self.env.cr.fetchall()
        if rate: #如果有涨价系数则对采购价格进行调整，并且根据是否选中更新成本价更新成本价格
            for s in sids:
                supplierinfo=self.env['product.supplierinfo'].browse(s)
                supplierinfo.product_tmpl_id.list_price=round(supplierinfo.product_tmpl_id.list_price*(1+rate),0)
                sinfo=supplierinfo.copy({
                    'price':supplierinfo.price*(1+rate),
                    'date_revised':fields.Date.today(),#将更新日期填入
                    'date_start':datestart,
                    'date_end':dateend,
                    'delay':delay
                })
                if self.cost_update: #如果要更新成本价
                    self.update_cost(sinfo)
        else: #如果涨价系数为0，并且选中更新成本价则只更新成本价格
            for s in sids:
                sinfo=self.env['product.supplierinfo'].browse(s)
                if self.cost_update: #如果要更新成本价
                    self.update_cost(sinfo)
 
            
        






